"""
阿里宝宝电商系统 - 命令行界面（CLI）
提供完整的命令行交互界面
"""

import os
import sys
from typing import Optional, List, Dict, Any
from core.services.auth_service import AuthService
from core.services.product_service import ProductService
from core.services.order_service import OrderService
from core.services.review_service import ReviewService
from core.services.recommendation_service import RecommendationService
from core.models.cart import ShoppingCart
from core.models.user import Customer
from core.models.product import Product
from core.models.order import Order, OrderStatus
from core.models.review import Review
from core.utils.logger import info, warning, error, debug
from core.utils.i18n import i18n, set_language

# ANSI 颜色代码
class Colors:
    """终端颜色"""
    RESET = '\033[0m'
    BOLD = '\033[1m'
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    MAGENTA = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'
    GRAY = '\033[90m'


class CLIApp:
    """命令行应用主类"""
    
    def __init__(self):
        """初始化CLI应用"""
        # 初始化服务
        self.auth_service = AuthService()
        self.product_service = ProductService()
        self.order_service = OrderService()
        self.review_service = ReviewService()
        self.recommendation_service = RecommendationService()
        
        # 当前用户（None表示游客）
        self.current_user = None
        self.shopping_cart = None
        
        # 初始化购物车（游客）
        self.shopping_cart = ShoppingCart(user_id="guest")
        
        # 初始化国际化
        try:
            from core.services.data_manager import DataManager
            dm = DataManager()
            settings = dm.load_data('settings.json') or {}
            language = settings.get('language', 'zh_CN')
            set_language(language)
        except Exception as e:
            warning(f"初始化语言失败: {e}")
    
    def clear_screen(self):
        """清屏"""
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def print_header(self, title: str):
        """打印标题"""
        print("\n" + "=" * 60)
        print(f"{Colors.CYAN}{Colors.BOLD}{title.center(60)}{Colors.RESET}")
        print("=" * 60)
    
    def print_success(self, message: str):
        """打印成功消息"""
        print(f"{Colors.GREEN}✓ {message}{Colors.RESET}")
    
    def print_error(self, message: str):
        """打印错误消息"""
        print(f"{Colors.RED}✗ {message}{Colors.RESET}")
    
    def print_warning(self, message: str):
        """打印警告消息"""
        print(f"{Colors.YELLOW}⚠ {message}{Colors.RESET}")
    
    def print_info(self, message: str):
        """打印信息消息"""
        print(f"{Colors.BLUE}ℹ {message}{Colors.RESET}")
    
    def read_input(self, prompt: str = "") -> str:
        """读取用户输入"""
        return input(f"{Colors.CYAN}{prompt}{Colors.RESET}").strip()
    
    def press_enter_to_continue(self):
        """按回车继续"""
        input(f"\n{Colors.GRAY}按 Enter 键继续...{Colors.RESET}")
    
    def print_menu(self, menu_items: List[str], title: str = "菜单"):
        """打印菜单"""
        self.print_header(title)
        for i, item in enumerate(menu_items, 1):
            print(f"{Colors.YELLOW}{i}.{Colors.RESET} {item}")
        print(f"{Colors.YELLOW}0.{Colors.RESET} 退出")
        print("-" * 60)
    
    def get_menu_choice(self, max_choice: int) -> int:
        """获取菜单选择"""
        while True:
            try:
                choice = self.read_input(f"\n请选择 (0-{max_choice}): ")
                choice_int = int(choice)
                if 0 <= choice_int <= max_choice:
                    return choice_int
                else:
                    self.print_error(f"请输入 0-{max_choice} 之间的数字")
            except ValueError:
                self.print_error("请输入有效的数字")
    
    def show_welcome(self):
        """显示欢迎界面"""
        self.clear_screen()
        print(f"\n{Colors.CYAN}{Colors.BOLD}")
        print("  ╔════════════════════════════════════════════╗")
        print("  ║         🛒 阿里宝宝电商系统 🛒             ║")
        print("  ║          Ali Bao Bao E-commerce           ║")
        print("  ╚════════════════════════════════════════════╝")
        print(f"{Colors.RESET}")
    
    def show_main_menu(self):
        """显示主菜单"""
        self.clear_screen()
        
        if self.current_user:
            self.show_welcome()
            print(f"\n{Colors.GREEN}已登录: {self.current_user.username} {Colors.RESET}")
            print(f"{Colors.GRAY}用户ID: {self.current_user.user_id}{Colors.RESET}\n")
            menu_items = [
                "浏览商品",
                "搜索商品",
                "查看我的购物车",
                "查看我的订单",
                "查看我的评价",
                "查看推荐商品",
                "登出"
            ]
            self.print_menu(menu_items, "用户菜单")
        else:
            self.show_welcome()
            menu_items = [
                "用户注册",
                "用户登录",
                "浏览商品",
                "搜索商品",
                "查看购物车",
            ]
            self.print_menu(menu_items, "游客菜单")
    
    def run(self):
        """运行CLI应用"""
        info("=== STARTING CLI ===")
        
        while True:
            self.show_main_menu()
            choice = self.get_menu_choice(7 if self.current_user else 5)
            
            if choice == 0:
                self.print_info("感谢使用阿里宝宝电商系统！再见！")
                sys.exit(0)
            
            if self.current_user:
                # 用户菜单
                if choice == 1:
                    self.browse_products()
                elif choice == 2:
                    self.search_products()
                elif choice == 3:
                    self.show_cart()
                elif choice == 4:
                    self.show_my_orders()
                elif choice == 5:
                    self.show_my_reviews()
                elif choice == 6:
                    self.show_recommendations()
                elif choice == 7:
                    self.logout()
            else:
                # 游客菜单
                if choice == 1:
                    self.register()
                elif choice == 2:
                    self.login()
                elif choice == 3:
                    self.browse_products()
                elif choice == 4:
                    self.search_products()
                elif choice == 5:
                    self.show_cart()
    
    # ============ 用户认证相关 ============
    
    def register(self):
        """用户注册"""
        self.clear_screen()
        self.print_header("用户注册")
        
        username = self.read_input("用户名: ")
        if not username:
            self.print_error("用户名不能为空")
            self.press_enter_to_continue()
            return
        
        email = self.read_input("邮箱: ")
        if not email:
            self.print_error("邮箱不能为空")
            self.press_enter_to_continue()
            return
        
        password = self.read_input("密码: ")
        if not password:
            self.print_error("密码不能为空")
            self.press_enter_to_continue()
            return
        
        # 验证密码强度
        from core.models.user import User
        is_valid, error_msg = User.validate_password_strength(password)
        if not is_valid:
            self.print_error(f"密码不符合要求: {error_msg}")
            self.press_enter_to_continue()
            return
        
        try:
            user = self.auth_service.register(username, email, password, role="customer")
            if user:
                self.print_success("注册成功！")
                self.current_user = user
                self.shopping_cart.update_user_id(user.user_id)
                info(f"用户注册成功: {username}")
            else:
                self.print_error("注册失败，用户名或邮箱可能已存在")
        except Exception as e:
            self.print_error(f"注册失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def login(self):
        """用户登录"""
        self.clear_screen()
        self.print_header("用户登录")
        
        username = self.read_input("用户名: ")
        if not username:
            self.print_error("用户名不能为空")
            self.press_enter_to_continue()
            return
        
        password = self.read_input("密码: ")
        if not password:
            self.print_error("密码不能为空")
            self.press_enter_to_continue()
            return
        
        try:
            user = self.auth_service.login(username, password)
            if user:
                self.print_success(f"登录成功！欢迎 {user.username}")
                self.current_user = user
                self.shopping_cart.update_user_id(user.user_id)
                info(f"用户登录成功: {username}")
            else:
                self.print_error("登录失败，用户名或密码错误")
        except Exception as e:
            self.print_error(f"登录失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def logout(self):
        """登出"""
        if self.current_user:
            self.print_info(f"再见，{self.current_user.username}！")
            self.current_user = None
            self.shopping_cart.update_user_id("guest")
            info("用户登出")
        
        self.press_enter_to_continue()
    
    # ============ 商品相关 ============
    
    def browse_products(self, category: Optional[str] = None):
        """浏览商品"""
        self.clear_screen()
        title = f"商品目录 - {category.upper()}" if category else "商品目录"
        self.print_header(title)
        
        try:
            products = self.product_service.get_all_products()
            
            if category:
                products = [p for p in products if p.get_category() == category]
            
            if not products:
                self.print_warning("没有找到商品")
                self.press_enter_to_continue()
                return
            
            # 分页显示
            page_size = 5
            page = 0
            
            while True:
                start = page * page_size
                end = start + page_size
                page_products = products[start:end]
                
                if not page_products:
                    self.print_info("没有更多商品了")
                    break
                
                # 显示商品
                for i, product in enumerate(page_products, 1):
                    self._print_product_summary(product)
                
                print(f"\n{Colors.GRAY}第 {page + 1} 页，共 {len(products)} 个商品{Colors.RESET}")
                
                # 查看详情选择
                choice = self.read_input("\n输入商品编号查看详情 (或 n 下一页/p 上一页/q 返回): ")
                choice = choice.lower()
                
                if choice == 'q':
                    break
                elif choice == 'n':
                    if end < len(products):
                        page += 1
                    else:
                        self.print_info("已经是最后一页了")
                elif choice == 'p':
                    if page > 0:
                        page -= 1
                    else:
                        self.print_info("已经是第一页了")
                elif choice.isdigit():
                    idx = int(choice) - 1
                    if 0 <= idx < len(page_products):
                        self.show_product_detail(page_products[idx])
                        break
                    else:
                        self.print_error("无效的商品编号")
                else:
                    self.print_error("无效的输入")
        
        except Exception as e:
            self.print_error(f"加载商品失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def search_products(self):
        """搜索商品"""
        self.clear_screen()
        self.print_header("搜索商品")
        
        keyword = self.read_input("请输入搜索关键词: ")
        if not keyword:
            return
        
        try:
            products = self.product_service.search_products(keyword)
            
            if not products:
                self.print_warning(f"没有找到包含 '{keyword}' 的商品")
                self.press_enter_to_continue()
                return
            
            self.clear_screen()
            self.print_header(f"搜索结果: {keyword}")
            
            for i, product in enumerate(products, 1):
                self._print_product_summary(product)
            
            choice = self.read_input("\n输入商品编号查看详情 (或 q 返回): ")
            if choice.lower() != 'q' and choice.isdigit():
                idx = int(choice) - 1
                if 0 <= idx < len(products):
                    self.show_product_detail(products[idx])
        
        except Exception as e:
            self.print_error(f"搜索失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def show_product_detail(self, product: Product):
        """显示商品详情"""
        self.clear_screen()
        self.print_header(f"商品详情 - {product.name}")
        
        print(f"\n{Colors.BOLD}{product.name}{Colors.RESET}")
        print(f"{Colors.GRAY}{product.description}{Colors.RESET}")
        print(f"\n{Colors.BLUE}商品ID:{Colors.RESET} {product.product_id}")
        print(f"{Colors.BLUE}类别:{Colors.RESET} {product.get_category()}")
        print(f"{Colors.BLUE}原价:{Colors.RESET} {Colors.YELLOW}¥{product.price:.2f}{Colors.RESET}")
        
        discount = product.calculate_discount()
        discounted_price = product.get_discounted_price()
        discount_rate = product.get_discount_rate()
        
        print(f"{Colors.BLUE}折扣率:{Colors.RESET} {Colors.GREEN}{discount_rate*100:.0f}%{Colors.RESET}")
        print(f"{Colors.BLUE}折扣后价格:{Colors.RESET} {Colors.GREEN}¥{discounted_price:.2f}{Colors.RESET}")
        print(f"{Colors.BLUE}库存:{Colors.RESET} {product.stock}")
        
        # 显示评价统计
        rating_stats = self.product_service.get_product_rating_stats(product.product_id)
        if rating_stats['total_reviews'] > 0:
            avg_rating = rating_stats['average_rating']
            print(f"\n{Colors.BLUE}评分:{Colors.RESET} {Colors.YELLOW}{avg_rating:.1f}/5.0{Colors.RESET} ({rating_stats['total_reviews']} 条评价)")
        
        # 查看评价
        choice = self.read_input("\n按 1 查看评价，按 2 添加到购物车，按其他键返回: ")
        
        if choice == '1':
            self.show_product_reviews(product.product_id)
        elif choice == '2':
            self.add_to_cart(product)
    
    def show_product_reviews(self, product_id: str):
        """显示商品评价"""
        self.clear_screen()
        self.print_header("商品评价")
        
        try:
            reviews = self.review_service.get_product_reviews(product_id)
            
            if not reviews:
                self.print_info("该商品还没有评价")
                self.press_enter_to_continue()
                return
            
            for review in reviews:
                print(f"\n{Colors.BOLD}{review.user_name or '匿名用户'}{Colors.RESET}")
                print(f"{Colors.YELLOW}{'★' * review.rating}{'☆' * (5 - review.rating)}{Colors.RESET}")
                print(f"{Colors.GRAY}{review.created_at}{Colors.RESET}")
                print(f"{review.comment}")
                if review.helpful_count > 0:
                    print(f"{Colors.GREEN}有用: {review.helpful_count}{Colors.RESET}")
                print("-" * 60)
            
        except Exception as e:
            self.print_error(f"加载评价失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def _print_product_summary(self, product: Product):
        """打印商品摘要"""
        discount_rate = product.get_discount_rate()
        discounted_price = product.get_discounted_price()
        
        rating_stats = self.product_service.get_product_rating_stats(product.product_id)
        avg_rating = rating_stats.get('average_rating', 0)
        review_count = rating_stats.get('total_reviews', 0)
        
        rating_display = f"{avg_rating:.1f}⭐ ({review_count})" if review_count > 0 else "暂无评价"
        
        print(f"\n{Colors.BOLD}{product.product_id}{Colors.RESET} - {Colors.CYAN}{product.name}{Colors.RESET}")
        print(f"  {Colors.GRAY}{product.description[:50]}...{Colors.RESET}")
        print(f"  {Colors.YELLOW}¥{product.price:.2f}{Colors.RESET} → {Colors.GREEN}¥{discounted_price:.2f}{Colors.RESET} (-{discount_rate*100:.0f}%)")
        print(f"  {Colors.BLUE}库存:{Colors.RESET} {product.stock}  {Colors.BLUE}评分:{Colors.RESET} {rating_display}")
    
    # ============ 购物车相关 ============
    
    def show_cart(self):
        """显示购物车"""
        self.clear_screen()
        self.print_header("我的购物车")
        
        if not self.shopping_cart.items:
            self.print_info("购物车是空的")
            self.press_enter_to_continue()
            return
        
        total = self.shopping_cart.total_price
        
        for i, item in enumerate(self.shopping_cart.items, 1):
            product = item.product
            subtotal = item.subtotal
            
            print(f"\n{i}. {Colors.CYAN}{product.name}{Colors.RESET}")
            print(f"   数量: {item.quantity} x ¥{product.price:.2f} = ¥{subtotal:.2f}")
            if product.stock < item.quantity:
                self.print_warning(f"   警告: 库存不足（库存: {product.stock}，需要: {item.quantity}）")
        
        print(f"\n{Colors.BOLD}{'=' * 60}{Colors.RESET}")
        print(f"{Colors.BOLD}总计: {Colors.GREEN}¥{total:.2f}{Colors.RESET}")
        print(f"{Colors.BOLD}{'=' * 60}{Colors.RESET}")
        
        choice = self.read_input("\n输入商品编号管理商品，或按 c 结账，按其他键返回: ")
        
        if choice.lower() == 'c':
            if self.current_user:
                self.checkout()
            else:
                self.print_error("请先登录")
                self.press_enter_to_continue()
        elif choice.isdigit():
            idx = int(choice) - 1
            if 0 <= idx < len(self.shopping_cart.items):
                self.manage_cart_item(self.shopping_cart.items[idx])
    
    def manage_cart_item(self, item):
        """管理购物车商品"""
        self.clear_screen()
        product = item.product
        self.print_header(f"管理 - {product.name}")
        
        print(f"\n商品: {Colors.CYAN}{product.name}{Colors.RESET}")
        print(f"当前数量: {item.quantity}")
        print(f"库存: {product.stock}")
        
        print("\n1. 修改数量")
        print("2. 删除商品")
        print("0. 返回")
        
        choice = self.read_input("\n请选择: ")
        
        if choice == '1':
            try:
                new_qty = int(self.read_input(f"新数量 (0-{product.stock}): "))
                if new_qty == 0:
                    self.shopping_cart.remove_item(product.product_id)
                    self.print_success("已从购物车移除")
                elif 0 < new_qty <= product.stock:
                    self.shopping_cart.update_quantity(product.product_id, new_qty)
                    self.print_success("数量已更新")
                else:
                    self.print_error("无效的数量")
            except ValueError:
                self.print_error("请输入有效的数字")
        elif choice == '2':
            self.shopping_cart.remove_item(product.product_id)
            self.print_success("已删除")
        
        self.press_enter_to_continue()
    
    def add_to_cart(self, product: Product):
        """添加到购物车"""
        if product.stock <= 0:
            self.print_error("商品库存不足")
            self.press_enter_to_continue()
            return
        
        try:
            qty = int(self.read_input(f"数量 (最多 {product.stock}): "))
            
            if qty <= 0 or qty > product.stock:
                self.print_error("无效的数量")
                self.press_enter_to_continue()
                return
            
            self.shopping_cart.add_item(product, qty)
            self.print_success(f"已添加 {qty} 个 {product.name} 到购物车")
            
        except ValueError:
            self.print_error("请输入有效的数字")
        except Exception as e:
            self.print_error(f"添加失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    # ============ 订单相关 ============
    
    def checkout(self):
        """结账"""
        if not self.current_user:
            self.print_error("请先登录")
            self.press_enter_to_continue()
            return
        
        if not self.shopping_cart.items:
            self.print_error("购物车是空的")
            self.press_enter_to_continue()
            return
        
        # 检查库存
        for item in self.shopping_cart.items:
            product = item.product
            if product.stock < item.quantity:
                self.print_error(f"{product.name} 库存不足（库存: {product.stock}，需要: {item.quantity}）")
                self.press_enter_to_continue()
                return
        
        self.clear_screen()
        self.print_header("确认订单")
        
        for item in self.shopping_cart.items:
            product = item.product
            print(f"\n{Colors.CYAN}{product.name}{Colors.RESET} x {item.quantity} = ¥{item.subtotal:.2f}")
        
        total = self.shopping_cart.total_price
        print(f"\n{Colors.BOLD}总计: ¥{total:.2f}{Colors.RESET}")
        
        confirm = self.read_input("\n确认下单？(y/n): ")
        
        if confirm.lower() == 'y':
            try:
                # 创建订单
                order_items = []
                for item in self.shopping_cart.items:
                    product = item.product
                    from core.models.order import OrderItem
                    order_item = OrderItem(
                        product_id=product.product_id,
                        product_name=product.name,
                        price=product.price,
                        quantity=item.quantity,
                        subtotal=item.subtotal
                    )
                    order_items.append(order_item)
                
                order = self.order_service.create_order(
                    user_id=self.current_user.user_id,
                    items=order_items,
                    total=total
                )
                
                if order:
                    self.print_success(f"订单创建成功！订单号: {order.order_id}")
                    info(f"订单创建成功: {order.order_id}")
                else:
                    self.print_error("订单创建失败")
                    
            except Exception as e:
                self.print_error(f"下单失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def show_my_orders(self):
        """查看我的订单"""
        if not self.current_user:
            self.print_error("请先登录")
            self.press_enter_to_continue()
            return
        
        self.clear_screen()
        self.print_header("我的订单")
        
        try:
            orders = self.order_service.get_user_orders(self.current_user.user_id)
            
            if not orders:
                self.print_info("您还没有订单")
                self.press_enter_to_continue()
                return
            
            for order in orders:
                self._print_order_summary(order)
            
            choice = self.read_input("\n输入订单号查看详情 (或 q 返回): ")
            
            if choice.lower() != 'q':
                order = self.order_service.get_order_by_id(choice)
                if order and order.user_id == self.current_user.user_id:
                    self.show_order_detail(order)
                else:
                    self.print_error("订单不存在")
                    self.press_enter_to_continue()
        
        except Exception as e:
            self.print_error(f"加载订单失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def show_order_detail(self, order: Order):
        """显示订单详情"""
        self.clear_screen()
        self.print_header(f"订单详情 - {order.order_id}")
        
        print(f"\n{Colors.BOLD}订单号:{Colors.RESET} {order.order_id}")
        print(f"{Colors.BOLD}状态:{Colors.RESET} {self._get_status_display(order.status)}")
        print(f"{Colors.BOLD}创建时间:{Colors.RESET} {order.created_at}")
        print(f"{Colors.BOLD}更新时间:{Colors.RESET} {order.updated_at}")
        
        print(f"\n{Colors.CYAN}订单商品:{Colors.RESET}")
        for item in order.items:
            print(f"  {item.product_name} x {item.quantity} = ¥{item.subtotal:.2f}")
        
        print(f"\n{Colors.BOLD}总计: ¥{order.total:.2f}{Colors.RESET}")
        
        # 如果是已完成的订单，允许发表评价
        if order.status == OrderStatus.COMPLETED:
            choice = self.read_input("\n按 1 发表评价，按其他键返回: ")
            if choice == '1':
                self.create_review(order)
        
        self.press_enter_to_continue()
    
    def _print_order_summary(self, order: Order):
        """打印订单摘要"""
        status_color = Colors.GREEN if order.status == OrderStatus.COMPLETED else \
                       Colors.YELLOW if order.status == OrderStatus.SHIPPED else \
                       Colors.RED if order.status == OrderStatus.CANCELLED else Colors.BLUE
        
        print(f"\n{Colors.BOLD}订单号: {order.order_id}{Colors.RESET}")
        print(f"  状态: {status_color}{self._get_status_display(order.status)}{Colors.RESET}")
        print(f"  商品数量: {order.item_count}")
        print(f"  总金额: {Colors.GREEN}¥{order.total:.2f}{Colors.RESET}")
        print(f"  时间: {Colors.GRAY}{order.created_at}{Colors.RESET}")
    
    def _get_status_display(self, status: OrderStatus) -> str:
        """获取状态显示文本"""
        status_map = {
            OrderStatus.PENDING: "待支付",
            OrderStatus.PAID: "已支付",
            OrderStatus.SHIPPED: "已发货",
            OrderStatus.COMPLETED: "已完成",
            OrderStatus.CANCELLED: "已取消"
        }
        return status_map.get(status, str(status))
    
    # ============ 评价相关 ============
    
    def create_review(self, order: Order):
        """创建评价"""
        if not order.items:
            self.print_error("订单中没有商品")
            self.press_enter_to_continue()
            return
        
        # 选择要评价的商品
        print("\n请选择要评价的商品:")
        for i, item in enumerate(order.items, 1):
            print(f"{i}. {item.product_name}")
        
        choice = self.read_input("\n请输入商品编号: ")
        
        if not choice.isdigit() or not (1 <= int(choice) <= len(order.items)):
            self.print_error("无效的选择")
            self.press_enter_to_continue()
            return
        
        selected_item = order.items[int(choice) - 1]
        product_id = selected_item.product_id
        
        # 检查是否已经评价过
        existing_reviews = self.review_service.get_user_product_review(
            self.current_user.user_id,
            product_id
        )
        
        if existing_reviews:
            self.print_warning("您已经评价过这个商品了")
            self.press_enter_to_continue()
            return
        
        self.clear_screen()
        self.print_header("发表评价")
        
        print(f"商品: {Colors.CYAN}{selected_item.product_name}{Colors.RESET}\n")
        
        rating = int(self.read_input("评分 (1-5 星): "))
        if not (1 <= rating <= 5):
            self.print_error("评分必须在 1-5 之间")
            self.press_enter_to_continue()
            return
        
        comment = self.read_input("评论内容: ")
        
        try:
            review = self.review_service.create_review(
                product_id=product_id,
                user_id=self.current_user.user_id,
                user_name=self.current_user.username,
                order_id=order.order_id,
                rating=rating,
                comment=comment
            )
            
            if review:
                self.print_success("评价发表成功！")
                info(f"评价创建成功: {review.review_id}")
            else:
                self.print_error("评价发表失败")
                
        except Exception as e:
            self.print_error(f"发表评价失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    def show_my_reviews(self):
        """显示我的评价"""
        if not self.current_user:
            self.print_error("请先登录")
            self.press_enter_to_continue()
            return
        
        self.clear_screen()
        self.print_header("我的评价")
        
        try:
            reviews = self.review_service.get_user_reviews(self.current_user.user_id)
            
            if not reviews:
                self.print_info("您还没有发表过评价")
                self.press_enter_to_continue()
                return
            
            for review in reviews:
                print(f"\n{Colors.CYAN}{review.product_id}{Colors.RESET}")
                print(f"{Colors.YELLOW}{'★' * review.rating}{'☆' * (5 - review.rating)}{Colors.RESET}")
                print(f"{review.comment}")
                print(f"{Colors.GRAY}{review.created_at}{Colors.RESET}")
                print("-" * 60)
        
        except Exception as e:
            self.print_error(f"加载评价失败: {str(e)}")
        
        self.press_enter_to_continue()
    
    # ============ 推荐系统相关 ============
    
    def show_recommendations(self):
        """显示推荐商品"""
        if not self.current_user:
            self.print_error("请先登录")
            self.press_enter_to_continue()
            return
        
        self.clear_screen()
        self.print_header("为您推荐")
        
        try:
            recommendations = self.recommendation_service.recommend_products(
                self.current_user.user_id,
                limit=5
            )
            
            if not recommendations:
                self.print_info("暂无推荐商品")
                self.press_enter_to_continue()
                return
            
            print(f"\n{Colors.YELLOW}根据您的购买历史推荐以下商品：{Colors.RESET}\n")
            
            for product in recommendations:
                self._print_product_summary(product)
            
        except Exception as e:
            self.print_error(f"加载推荐失败: {str(e)}")
        
        self.press_enter_to_continue()


def main():
    """主函数"""
    app = CLIApp()
    
    try:
        app.run()
    except KeyboardInterrupt:
        print(f"\n\n{Colors.YELLOW}程序被用户中断{Colors.RESET}")
        sys.exit(0)
    except Exception as e:
        error(f"CLI 运行失败: {e}")
        print(f"\n{Colors.RED}程序发生错误: {str(e)}{Colors.RESET}")
        sys.exit(1)


if __name__ == "__main__":
    main()

